﻿namespace DesignModeConsole.行为型.观察者模式;

/// <summary>
/// 用户控制器
/// </summary>
public class UserController
{
    private List<RegObserver> RegObservers = new List<RegObserver>();

    public void SetRegObservers(List<RegObserver> observers)
    {
        RegObservers.AddRange(observers);
    }

    /// <summary>
    /// 注册接口（注册成功后发送邮件和短信通知）
    /// </summary>
    /// <param name="userName"></param>
    /// <returns></returns>
    public long Register(string userName)
    {
        // 校验以及注册用户
        var userId = 123456L;

        // 注册成功后发送邮件和短信
        foreach (var observer in RegObservers)
        {
            observer.HandleRegSuccess(userId);
        }

        return userId;
    }
}

/// <summary>
/// 用户控制器
/// </summary>
public class UserController2
{
    private List<RegObserver> RegObservers = new List<RegObserver>();

    public void SetRegObservers(List<RegObserver> observers)
    {
        RegObservers.AddRange(observers);
    }

    /// <summary>
    /// 注册接口（注册成功后发送邮件和短信通知）
    /// </summary>
    /// <param name="userName"></param>
    /// <returns></returns>
    public long Register(string userName)
    {
        // 校验以及注册用户
        var userId = 123456L;

        // 注册成功后发送邮件和短信
        foreach (var observer in RegObservers)
        {
            Task.Run(() =>
            {
                observer.HandleRegSuccess(userId);
            });
        }

        Console.WriteLine("注册完成");

        return userId;
    }
}

public interface RegObserver
{
    /// <summary>
    /// 注册成功
    /// </summary>
    /// <param name="userId"></param>
    void HandleRegSuccess(long userId);
}

public class SendEmailObserver : RegObserver
{
    public void HandleRegSuccess(long userId)
    {
        Console.WriteLine($"发送邮件给用户：{userId}");
    }
}

public class SendSmsObserver : RegObserver
{
    public void HandleRegSuccess(long userId)
    {
        Console.WriteLine($"发送短信给用户：{userId}");
    }
}